#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/20
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from flask import url_for
from flask_socketio import Namespace, emit
from project.flasky import socketio
from project.define import conn_logger
from project.prepare import CarParkService


class CarParkNamespace(Namespace):
    def on_connect(self):
        pass

    def on_disconnect(self):
        pass

    def on_cameras_event(self, data):
        """
        相机事件
        """
        conn_logger.debug(f"socketio接收：{data}")
        q = CarParkService.CameraSocketQ
        while True:
            try:
                if not q.empty():
                    status = q.get()
                    image = status.get('LicensePlateImg')
                    if image:
                        status['LicensePlateImg'] = url_for('static', filename=image)
                    emit("cameras_status", {'status': status}, broadcast=True)
            except Exception as e:
                conn_logger.error(f"socketio发送失败：{e}")
                break
            socketio.sleep(1)

    def on_lanes_event(self, data):
        """
        车道事件
        """
        conn_logger.debug(f"socketio接收：{data}")
        q = CarParkService.LaneSocketQ
        while True:
            try:
                if not q.empty():
                    status = q.get()
                    image = status.get('LicensePlateImg')
                    if image:
                        status['LicensePlateImg'] = url_for('static', filename=image)
                    emit("lanes_status", {'status': status}, broadcast=True)
            except Exception as e:
                conn_logger.error(f"socketio发送失败：{e}")
                break
            socketio.sleep(1)

    def on_places_event(self, data):
        """
        车位
        """
        conn_logger.debug(f"socketio接收：{data}")
        q = CarParkService.PlaceSocketQ
        while True:
            try:
                if not q.empty():
                    status = q.get()
                    emit("places_status", {'status': status}, broadcast=True)
            except Exception as e:
                conn_logger.error(f"socketio发送失败：{e}")
                break
            socketio.sleep(1)

socketio.on_namespace(CarParkNamespace("/carpark_status"))
